<template>
  <div class="container">
    <div class="header">
      <h1>添加讲师</h1>
    </div>
    
    <el-card class="form-card">
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px" 
        class="instructor-form"
      >
        <el-form-item label="姓名" prop="teacherName">
          <el-input v-model="form.teacherName" placeholder="请输入讲师姓名" />
        </el-form-item>
        
        <el-form-item label="头像" prop="teacherHeaderUrl">
          <div class="avatar-uploader">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleAvatarChange"
              :before-upload="beforeAvatarUpload"
            >
              <div class="avatar-container">
                <img
                  v-if="form.teacherHeaderUrl"
                  :src="form.teacherHeaderUrl"
                  class="avatar"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </div>
            </el-upload>
            <div v-if="form.teacherHeaderUrl" class="preview-actions">
              <el-button 
                type="primary" 
                @click="previewImage(form.teacherHeaderUrl)"
                size="small">
                <el-icon><ZoomIn /></el-icon> 预览大图
              </el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="个人简介" prop="teacherDescription">
          <el-input 
            v-model="form.teacherDescription" 
            type="textarea" 
            :rows="5" 
            placeholder="请输入个人简介"
          />
        </el-form-item>
        
        <el-form-item label="课程描述" prop="teahcerLessonDescription">
          <el-input 
            v-model="form.teahcerLessonDescription" 
            type="textarea" 
            :rows="5" 
            placeholder="请输入课程描述"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="头像预览" width="400px" append-to-body center>
      <div class="image-preview-dialog">
        <el-image
          style="width: 100%;"
          :src="previewImageUrl"
          fit="contain"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { addTeacher, uploadTeacherAvatar } from '@/api/teacher'
import { Plus, ZoomIn } from '@element-plus/icons-vue'

const router = useRouter()
const formRef = ref(null)
const submitting = ref(false)

const form = reactive({
  teacherName: '',
  teacherHeaderUrl: '',
  teacherDescription: '',
  teahcerLessonDescription: '',
  teacherLikeNumbers: 0,
  deleteFlag: 0
})

const rules = reactive({
  teacherName: [
    { required: true, message: '请输入讲师姓名', trigger: 'blur' }
  ],
  teacherHeaderUrl: [
    { required: true, message: '请上传头像', trigger: 'change' }
  ],
  teacherDescription: [
    { required: true, message: '请输入个人简介', trigger: 'blur' }
  ]
})

// 头像文件引用
const avatarFile = ref(null)

// 头像更改处理 - 只预览不上传
const handleAvatarChange = (file) => {
  if (!file || !file.raw) return
  
  avatarFile.value = file.raw
  
  // 本地预览
  const reader = new FileReader()
  reader.onload = (e) => {
    form.teacherHeaderUrl = e.target.result
  }
  reader.readAsDataURL(avatarFile.value)
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const previewVisible = ref(false)
const previewImageUrl = ref('')

// 预览图片
const previewImage = (url) => {
  if (!url) return
  previewImageUrl.value = url
  previewVisible.value = true
}

const submitForm = async () => {
  const valid = await formRef.value.validate().catch(() => false)
  
  if (valid) {
    submitting.value = true
    try {
      // 如果选择了头像，先上传头像
      if (avatarFile.value) {
        const response = await uploadTeacherAvatar(avatarFile.value)
        if (response.code === 200) {
          // 处理返回的文件路径（从message中获取，并去除多余空格）
          const avatarPath = response.message ? response.message.replace(/\s+/g, '') : ''
          // 构建完整URL，确保路径没有多余空格
          form.teacherHeaderUrl = `http://localhost:8080/api${avatarPath}`
          console.log('头像地址:', form.teacherHeaderUrl)
          ElMessage.success('头像上传成功')
        } else {
          throw new Error(response.message || '头像上传失败')
        }
      }
      
      const response = await addTeacher(form)
      if (response.code === 200) {
        ElMessage.success('讲师添加成功')
        router.push('/instructor')
      } else {
        ElMessage.error(response.message || '讲师添加失败')
      }
    } catch (error) {
      ElMessage.error('讲师添加失败: ' + (error.message || '未知错误'))
      console.error(error)
    } finally {
      submitting.value = false
    }
  }
}

const cancel = () => {
  router.push('/instructor')
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
  
  .header {
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
  }
  
  .form-card {
    margin-bottom: 20px;
  }
  
  .instructor-form {
    max-width: 600px;
    margin-top: 20px;
  }
  
  .avatar-uploader {
    text-align: center;
    
    .avatar-container {
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    
    .preview-actions {
      margin-top: 10px;
    }
    
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
      border-radius: 50%;
      object-fit: cover;
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 50%;
      cursor: pointer;
    }
  }

  .image-preview-dialog {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }
}
</style> 